import time
import json
from asyncio import sleep
import datetime
import telebot
import redis

from llm_response.llm_response import ask_llm_re_country_name, ask_llm20_1, \
    ask_qwen_video_payout_reversal, ask_qwen_img_utr
from uitls.parse.parse_order import parse_order_ids
from uitls.reqquests_post import get_payment_inquiry_openmakeup, get_payment_inquiry_pdf, get_payment_inquiry_img
from uitls.save_files.save_file import save_file

# Bot Token
TOKEN = '7702930752:AAGYV0-kGJgMTavSPKxqdgo8tkR_gdthYJI'
bot = telebot.TeleBot(TOKEN)

# 连接本地 Redis（默认端口 6379）
r = redis.Redis(host='127.0.0.1', port=6379, db=0, password='yb@123456')
# r = redis.Redis(host='127.0.0.1', port=6379, db=0, password=None)
#
def payout_reversal(message):
    # 代付冲正
    saved_vids_file_id = []
    file_id = message.video.file_id
    saved_vids_file_id.append(file_id)
    timestamp = time.strftime("%Y%m%d%H%M%S")

    filename = f"{timestamp}_viedo.mp4"
    save_dir = rf"/home/admin/data/data/aicustomer-service/source_files/videos"
    # save_dir = "D:\\yuanbei\\客服问答机器人需求表\\source_files\\videos"
    save_path = save_file(save_dir, file_id, filename)
    country_name = ask_llm_re_country_name(message.chat.title)
    if country_name != "无":
        try:
            data_address = json.loads(country_name)
        except json.JSONDecodeError:
            print("不是 JSON，原始输出：", country_name)
            data_address = {"address": "", "mid": ""}  # 兜底，直接包一层
        sleep(21)
        text = message.caption
        print("data_address", data_address)
        order_ids = ask_llm20_1(text)
        order_data_ids = parse_order_ids(order_ids)
        print("order_id:", order_data_ids)
        data_payoutOrder = get_payment_inquiry_pdf(data_address, order_data_ids['order_ids'][0])
        print("代付冲正订单号data_payoutOrder", data_payoutOrder)
        try:
            parsed = json.loads(data_payoutOrder)  # 先把 JSON 字符串转成字典
        except json.JSONDecodeError:
            print("不是 JSON，原始输出：", data_payoutOrder)
            parsed = {"status": 201}  # 先把 JSON 字符串转成字

        payout_reversal_vid =ask_qwen_video_payout_reversal(save_path,data_payoutOrder)
        if payout_reversal_vid is not None:
            data1 = {
                "chat_id": message.chat.id,
                "message_id": message.message_id,
            }
            r.set("1", json.dumps(data1), ex=3600)

        try:
            payout_reversal_vid_json = json.loads(payout_reversal_vid)  # 先把 JSON 字符串转成字典
        except json.JSONDecodeError:
            print("不是 JSON，原始输出：", payout_reversal_vid)
            payout_reversal_vid_json = {"status": 201}  # 先把 JSON 字符串转成字

        if data_address['address'] != "":
            if parsed['status'] == 200:
                order_sn = parsed['data']['orderInfo']['order_sn']
                trade_sn = parsed['data']['orderInfo']['trade_sn']
                amount = parsed['data']['orderInfo']['amount']
                timestamp = parsed['data']['orderInfo']['instime']
                dt = datetime.datetime.fromtimestamp(timestamp)
                order_time = dt.strftime("%Y/%m/%d %H:%M:%S")
                if parsed['data']['orderInfo']['status'] == 1 or parsed['data']['orderInfo']['status'] == 3:
                    bot.reply_to(message, f'''
                        成功的无需补单操作\n\nDeepay单号：{order_sn}\n商户单号：{trade_sn}\n流水号：{payout_reversal_vid}\n订单金额：{amount}\n状态：{"成功的无需补单操作"}\n订单时间:{order_time}
                                                ''')
                else:
                    l = len(parsed['data']['orderInfo']['payoutSourceOrders'])
                    if l != 0:
                        if payout_reversal_vid_json['video_order_equal']=="n":

                            bot.reply_to(message, f'''
                                                            已反馈核查，有最新结果同步您\n\nDeepay单号：{order_sn}\n商户单号：{trade_sn}\n流水号：{""}\n流水时间：{payout_reversal_vid_json['video_max_time']}\n流水金额：{payout_reversal_vid_json['video_amount']}\n订单金额：{amount}\n状态：{"流水时间和金额对不上"}\n订单时间:{order_time}
                                                                            ''')
                            group_chat_id = -4805059187
                            # 发送图片
                            upstream = parsed['data']['orderInfo']['payoutSourceOrders'][l - 1]['order_ref']
                            bot.send_video(group_chat_id,
                                           saved_vids_file_id[0],
                                           caption=f'''单号：{upstream}\n用户反馈没有收到麻烦核查下这笔订单是否退回？'''
                                           )
                            print("请联系上游")
                        else:
                            bot.reply_to(message, f'''
                                                   成功的无需补单操作\n\nDeepay单号：{order_sn}\n商户单号：{trade_sn}\n流水号：{'流水时间：'+payout_reversal_vid_json['video_max_time']+',流水金额：'+payout_reversal_vid_json['video_amount']}\n订单金额：{amount}\n状态：{"成功的无需补单操作"}\n订单时间:{order_time}
                                                                           ''')
                    else:
                        bot.reply_to(message, "没有上游订单号")
                        print("没有上游订单号")
            else:
                bot.reply_to(message, "接口调不通，请重新查看接口。")
                print("接口调不通，请重新查看接口。")
        else:
            bot.reply_to(message, "没有提取到国家名称，需要请重新发一下")
            print("没有提取到国家名称，需要请重新发一下")
    else:
        raw = r.get("1")
        if raw:
            data = json.loads(raw)
            bot.send_photo(data["chat_id"],
                           saved_vids_file_id[0],
                           reply_to_message_id=data["message_id"]
                           )
        else:
            bot.reply_to(message, "没有提取到国家名称，需要请重新发一下")
            print("没有提取到国家名称，需要请重新发一下")


def payout_reversal_anim(message):
    # 代付冲正
    saved_vids_file_id = []
    text = message.caption
    file_id = message.animation.file_id
    saved_vids_file_id.append(file_id)
    timestamp = time.strftime("%Y%m%d%H%M%S")
    filename = f"{timestamp}_viedo.mp4"
    save_dir = rf"/home/admin/data/data/aicustomer-service/source_files/videos"
    # save_dir = "D:\\yuanbei\\客服问答机器人需求表\\source_files\\videos"
    save_path = save_file(save_dir, file_id, filename)
    country_name = ask_llm_re_country_name(message.chat.title)
    try:
        data_address = json.loads(country_name)
    except json.JSONDecodeError:
        print("不是 JSON，原始输出：", country_name)
        data_address = {"address": "", "mid": ""}  # 兜底，直接包一层
    if country_name != "无":
        if data_address['address'] != "":
            try:
                data_address = json.loads(country_name)
            except json.JSONDecodeError:
                print("不是 JSON，原始输出：", country_name)
                data_address = {"address": "", "mid": ""}  # 兜底，直接包一层
            sleep(21)
            text = message.caption
            print("data_address", data_address)
            order_ids = ask_llm20_1(text)
            order_data_ids = parse_order_ids(order_ids)
            print("order_id:", order_data_ids)
            data_payoutOrder = get_payment_inquiry_pdf(data_address, order_data_ids['order_ids'][0])
            print("代付冲正订单号data_payoutOrder", data_payoutOrder)
            try:
                parsed = json.loads(data_payoutOrder)  # 先把 JSON 字符串转成字典
            except json.JSONDecodeError:
                print("不是 JSON，原始输出：", data_payoutOrder)
                parsed = {"status": 201}  # 先把 JSON 字符串转成字

            payout_reversal_vid = ask_qwen_video_payout_reversal(save_path, data_payoutOrder)

            try:
                payout_reversal_vid_json = json.loads(payout_reversal_vid)  # 先把 JSON 字符串转成字典
            except json.JSONDecodeError:
                print("不是 JSON，原始输出：", payout_reversal_vid)
                payout_reversal_vid_json = {"status": 201}  # 先把 JSON 字符串转成字

            if parsed['status'] == 200:
                order_sn = parsed['data']['orderInfo']['order_sn']
                trade_sn = parsed['data']['orderInfo']['trade_sn']
                amount = parsed['data']['orderInfo']['amount']
                timestamp = parsed['data']['orderInfo']['instime']
                dt = datetime.datetime.fromtimestamp(timestamp)
                order_time = dt.strftime("%Y/%m/%d %H:%M:%S")
                if parsed['data']['orderInfo']['status'] == 1 or parsed['data']['orderInfo']['status'] == 3:
                    bot.reply_to(message, f'''
                        成功的无需补单操作\n\nDeepay单号：{order_sn}\n商户单号：{trade_sn}\n流水号：{payout_reversal_vid}\n订单金额：{amount}\n状态：{"成功的无需补单操作"}\n订单时间:{order_time}
                                                ''')
                else:
                    l = len(parsed['data']['orderInfo']['payoutSourceOrders'])
                    if l != 0:
                        if payout_reversal_vid_json['video_order_equal']=="n":

                            bot.reply_to(message, f'''
                                                            已反馈核查，有最新结果同步您\n\nDeepay单号：{order_sn}\n商户单号：{trade_sn}\n流水号：{""}\n流水时间：{payout_reversal_vid_json['video_max_time']}\n流水金额：{payout_reversal_vid_json['video_amount']}\n订单金额：{amount}\n状态：{"流水时间和金额对不上"}\n订单时间:{order_time}
                                                                            ''')
                            group_chat_id = -4805059187
                            # 发送图片
                            upstream = parsed['data']['orderInfo']['payoutSourceOrders'][l - 1]['order_ref']
                            bot.send_video(group_chat_id,
                                           saved_vids_file_id[0],
                                           caption=f'''单号：{upstream}\n用户反馈没有收到麻烦核查下这笔订单是否退回？'''
                                           )
                            print("请联系上游")
                        else:
                            bot.reply_to(message, f'''
                                                   成功的无需补单操作\n\nDeepay单号：{order_sn}\n商户单号：{trade_sn}\n流水号：{'流水时间：'+payout_reversal_vid_json['video_max_time']+',流水金额：'+payout_reversal_vid_json['video_amount']}\n订单金额：{amount}\n状态：{"成功的无需补单操作"}\n订单时间:{order_time}
                                                                           ''')
                    else:
                        bot.reply_to(message, "没有上游订单号")
                        print("没有上游订单号")
            else:
                bot.reply_to(message, "接口调不通，请重新查看接口。")
                print("接口调不通，请重新查看接口。")
        else:
            bot.reply_to(message, "没有提取到国家名称，需要请重新发一下")
            print("没有提取到国家名称，需要请重新发一下")


def payout_reversal_photos(message):
    saved_imgs_file_id = []
    text = message.caption
    timestamp = time.strftime("%Y%m%d%H%M%S")
    file_id = message.photo[-1].file_id
    saved_imgs_file_id.append(file_id)
    filename = f"{timestamp}_img.jpg"
    save_dir = rf"/home/admin/data/data/aicustomer-service/source_files/imgs"
    # save_dir = "D:\\yuanbei\\客服问答机器人需求表\\source_files\\imgs"
    save_path = save_file(save_dir, file_id, filename)
    country_name = ask_llm_re_country_name(message.chat.title)
    try:
        data_address = json.loads(country_name)
    except json.JSONDecodeError:
        print("不是 JSON，原始输出：", country_name)
        data_address = {"address": "", "mid": ""}  # 兜底，直接包一层
    sleep(21)
    if country_name != "无":
        if data_address['address'] != "":
            print("data_address", data_address)
            order_ids = ask_llm20_1(text)
            order_data_ids = parse_order_ids(order_ids)
            print("order_id:", order_data_ids['order_ids'][0])
            data_payoutOrder = get_payment_inquiry_img(data_address, order_data_ids['order_ids'][0])
            print("data_payoutOrder1", data_payoutOrder)
            try:
                if data_payoutOrder is None:
                    parsed = {"status": 201}  # 先把 JSON 字符串转成字典
                else:
                    parsed = json.loads(data_payoutOrder)  # 先把 JSON 字符串转成字典
            except json.JSONDecodeError:
                print("不是 JSON，原始输出：", data_payoutOrder)
                parsed = {"status": 201}  # 先把 JSON 字符串转成字典
            img_utr = ask_qwen_img_utr(save_path)
            print("img_utr+++++++++++++++++++++++++++++++++++++++", img_utr)
            if parsed['status'] == 200:
                order_sn = parsed['data']['orderInfo']['order_sn']
                trade_sn = parsed['data']['orderInfo']['trade_sn']
                amount = parsed['data']['orderInfo']['amount']
                timestamp = parsed['data']['orderInfo']['instime']
                dt = datetime.datetime.fromtimestamp(timestamp)
                order_time = dt.strftime("%Y/%m/%d %H:%M:%S")
                print("utr", img_utr)
                if parsed['data']['orderInfo']['status'] == 1 or parsed['data']['orderInfo']['status'] == 3:
                    bot.reply_to(message, f'''
                                成功的无需补单操作\n\nDeepay单号：{order_sn}\n商户单号：{trade_sn}\n流水号：{img_utr}\n订单金额：{amount}\n状态：{"成功的无需补单操作"}\n订单时间:{order_time}
                                                        ''')
                    print("成功的无需补单操作")
                else:
                    make_up_order = json.loads(
                        get_payment_inquiry_openmakeup(data_address, order_data_ids['order_ids'][0], img_utr))
                    print("make_up_order", make_up_order)
                    print("utr", img_utr)
                    l = len(parsed['data']['orderInfo']['sourceOrders'])
                    if make_up_order['status'] == 200:
                        bot.reply_to(message, f'''
                                    订单补单成功\n\nDeepay单号：{order_sn}\n商户单号：{trade_sn}\n流水号：{img_utr}\n订单金额：{amount}\n状态：{"订单补单成功"}\n订单时间:{order_time}
                                                        ''')
                        print("订单补单成功")
                    if make_up_order['status'] == 17510:
                        bot.reply_to(message, f'''
                                    订单状态错误\n\nDeepay单号：{order_sn}\n商户单号：{trade_sn}\n流水号：{img_utr}\n订单金额：{amount}\n状态：{"订单状态错误"}\n订单时间:{order_time}
                                                        ''')
                        print("订单状态错误")
                    if make_up_order['status'] == 17511:
                        bot.reply_to(message, f'''
                                    SYSTEM_EXCEPT_ERROR\n\nDeepay单号：{order_sn}\n商户单号：{trade_sn}\n流水号：{img_utr}\n订单金额：{amount}\n状态：{"SYSTEM_EXCEPT_ERROR"}\n订单时间:{order_time}
                                                        ''')
                        print("SYSTEM_EXCEPT_ERROR")
                    if make_up_order['status'] == -2:
                        bot.reply_to(message, f'''
                                    已反馈核查，有最新结果同步您\n\nDeepay单号：{order_sn}\n商户单号：{trade_sn}\n流水号：{img_utr}\n订单金额：{amount}\n状态：{"暂未收到"}\n订单时间:{order_time}
                                                        ''')
                        group_chat_id = -4805059187
                        upstream = parsed['data']['orderInfo']['sourceOrders'][l - 1]['order_ref']
                        bot.send_photo(group_chat_id,
                                       saved_imgs_file_id[0],
                                       caption=f'''单号：{upstream}\n用户反馈没有收到麻烦核查下这笔订单是否退回？'''
                                       )
                    if l != 0:
                        if make_up_order['status'] == 10001:
                            bot.reply_to(message, f'''
                                        已反馈核查，有最新结果同步您\n\nDeepay单号：{order_sn}\n商户单号：{trade_sn}\n流水号：{img_utr}\n订单金额：{amount}\n状态：{"暂未收到"}\n订单时间:{order_time}
                                                        ''')
                            group_chat_id = -4805059187
                            # 发送图片
                            upstream = parsed['data']['orderInfo']['sourceOrders'][l - 1]['order_ref']
                            data1 = {
                                "chat_id": message.chat.id,
                                "message_id": message.message_id,
                                "order_id": order_data_ids['order_ids'][0]
                            }
                            r.set(upstream, json.dumps(data1), ex=3600)
                            bot.send_photo(group_chat_id,
                                           saved_imgs_file_id[0],
                                           caption=f'''单号：{upstream}\n用户反馈没有收到麻烦核查下这笔订单是否退回？'''
                                           )
                    else:
                        bot.reply_to(message, "没有上游订单号")
                        print("没有上游订单号")
            else:
                bot.reply_to(message, "接口调不通，请重新查看接口。")
                print("接口调不通，请重新查看接口。")
        else:
            bot.reply_to(message, "没有提取到国家名称，需要请重新发一下")
            print("没有提取到国家名称，需要请重新发一下")
    else:
        # 1. 是否回复了消息
        if hasattr(message, "reply_to_message") and message.reply_to_message:
            if message.reply_to_message.caption is not None:
                order_ids = ask_llm20_1(message.reply_to_message.caption)
                order_ids_data = parse_order_ids(order_ids)
                raw = r.get(order_ids_data['order_ids'][0])
                if text is None:
                    text_content = ""
                else:
                    text_content = text
                if raw:
                    data = json.loads(raw)
                    bot.send_photo(data["chat_id"],
                                   saved_imgs_file_id[0],
                                   reply_to_message_id=data["message_id"],
                                   caption=f'''单号：{data['order_id']},{text_content}'''
                                   )
            elif message.reply_to_message.text is not None:
                order_ids = ask_llm20_1(message.reply_to_message.text)
                order_ids_data = parse_order_ids(order_ids)
                raw = r.get(order_ids_data['order_ids'][0])
                if text is None:
                    text_content = ""
                else:
                    text_content = text
                if raw:
                    print("redis获取到的order_id", r.get("order_id"))
                    data = json.loads(raw)
                    bot.send_photo(data["chat_id"],
                                   saved_imgs_file_id[0],
                                   reply_to_message_id=data["message_id"],
                                   caption=f'''单号：{data['order_id']},{text_content}'''
                                   )
            else:
                print("redis没有找到值")
